import LoginDescInfo from '@/pages/User/Login/components/LoginDescInfo';
import LoginDescTitle from '@/pages/User/Login/components/LoginDescTitle';
import { login } from '@/services/ant-design-pro/api';
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import { ArrowRightOutlined, LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { Helmet, history, useModel } from '@umijs/max';
import { Card, Col, Form, Image, Input, message, Modal, Row, Tabs } from 'antd';
import { createStyles } from 'antd-style';
import Link from 'antd/es/typography/Link';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';

const useStyles = createStyles(() => {
  return {
    container: {
      position: 'relative',
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
    logo: {
      position: 'absolute',
      top: '10px',
      left: '10px',
      width: '100px',
      height: '100px',
      backgroundImage:
        "url('https://image.so.com/view?q=%E6%B1%A4%E5%A7%86&src=tab_www&correct=%E6%B1%A4%E5%A7%86&ancestor=list&cmsid=705f3d7e77eff313aa07d709b82a1c2d&cmras=0&cn=0&gn=0&kn=0&crn=0&bxn=20&fsn=80&cuben=0&pornn=0&manun=24&adstar=0&clw=283#id=fbf83365d3fec9be6ea2ab97e512562e&currsn=0&ps=105&pc=105')",
    },
  };
});

const Login: React.FC = () => {
  const [type, setType] = useState<string>('account');
  const [verifyOpen, setVerifyOpen] = useState(false);
  const [verifyCode, setVerifyCode] = useState<string>('');
  const [verifyConfirmLoading, setVerifyConfirmLoading] = useState(false);
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const [userLoginForm, setUserLoginForm] = useState<API.LoginParams>();

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };
  const loginSubmit = async (values: API.LoginParams) => {
    setUserLoginForm(values);
    setVerifyOpen(true);
  };

  const verifySubmit = async () => {
    setVerifyConfirmLoading(true);
    // 登录
    const msg = await login({
      ...userLoginForm,
      type,
    });
    if (msg.status === 'ok') {
      const defaultLoginSuccessMessage = '登录成功！';
      message.success(defaultLoginSuccessMessage);
      await fetchUserInfo();
      const urlParams = new URL(window.location.href).searchParams;
      history.push(urlParams.get('redirect') || '/');
      return;
    }
    setVerifyOpen(false);
    setVerifyConfirmLoading(false);
  };

  const verifyCancel = () => {
    setVerifyCode('');
    setVerifyOpen(false);
    setVerifyConfirmLoading(false);
  };

  return (
    <div className={styles.container}>
      <Helmet>
        <title>{'登录 - 灵动创意工坊综合管理平台'}</title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}
      >
        <Card
          style={{
            width: 800,
            height: 500,
            backgroundColor: 'rgba(255, 255, 255, 0.6)',
          }}
          styles={{
            body: {
              padding: 0,
            },
          }}
        >
          <Row>
            <Col span={8}>
              <LoginDescInfo />
            </Col>
            <Col span={16} style={{ padding: 25 }}>
              <LoginDescTitle />
              <LoginForm
                containerStyle={{
                  height: 'auto',
                }}
                onFinish={async (values) => {
                  await loginSubmit(values as API.LoginParams);
                }}
              >
                <Tabs
                  activeKey={type}
                  onChange={setType}
                  centered
                  items={[
                    {
                      key: 'account',
                      label: '账户密码登录',
                    },
                    {
                      key: 'email',
                      label: '邮箱验证码登录',
                    },
                  ]}
                />
                {type === 'account' && (
                  <>
                    <ProFormText
                      name="username"
                      fieldProps={{
                        size: 'large',
                        prefix: <UserOutlined />,
                      }}
                      placeholder={'请输入用户名'}
                      rules={[
                        {
                          required: true,
                          message: '用户名是必填项！',
                        },
                      ]}
                    />
                    <ProFormText.Password
                      name="password"
                      fieldProps={{
                        size: 'large',
                        prefix: <LockOutlined />,
                      }}
                      placeholder={'请输入密码'}
                      rules={[
                        {
                          required: true,
                          message: '密码是必填项！',
                        },
                      ]}
                    />
                  </>
                )}

                {type === 'email' && (
                  <>
                    <ProFormText
                      fieldProps={{
                        size: 'large',
                        prefix: <MobileOutlined />,
                      }}
                      name="mobile"
                      placeholder={'请输入邮箱地址'}
                      rules={[
                        {
                          required: true,
                          message: '邮箱是必填项！',
                        },
                      ]}
                    />
                    <ProFormCaptcha
                      fieldProps={{
                        size: 'large',
                        prefix: <LockOutlined />,
                      }}
                      captchaProps={{
                        size: 'large',
                      }}
                      placeholder={'请输入验证码'}
                      captchaTextRender={(timing, count) => {
                        if (timing) {
                          return `${count} ${'秒后重新获取'}`;
                        }
                        return '获取验证码';
                      }}
                      name="captcha"
                      rules={[
                        {
                          required: true,
                          message: '验证码是必填项！',
                        },
                      ]}
                      onGetCaptcha={async (phone) => {
                        const result = await getFakeCaptcha({
                          phone,
                        });
                        if (!result) {
                          return;
                        }
                        message.success('获取验证码成功！');
                      }}
                    />
                  </>
                )}
                <div
                  style={{
                    marginBottom: 24,
                  }}
                >
                  <ProFormCheckbox noStyle name="autoLogin">
                    自动登录
                  </ProFormCheckbox>
                  <a
                    style={{
                      float: 'right',
                    }}
                    onClick={() => {
                      history.push('/user/join');
                    }}
                  >
                    <ArrowRightOutlined /> 加入我们
                  </a>
                </div>
              </LoginForm>
              <div
                style={{
                  fontSize: 14,
                  width: '100%',
                  textAlign: 'center',
                  left: 0,
                  color: '#6f6f6f',
                  position: 'absolute',
                  bottom: 30,
                }}
              >
                点击登录即代表同意我们的<Link>隐私政策</Link>与<Link>用户协议</Link>
              </div>
            </Col>
          </Row>
        </Card>
        <div
          style={{
            fontSize: 14,
            textAlign: 'center',
            marginTop: 10,
            color: '#6f6f6f',
            position: 'absolute',
            bottom: 20,
          }}
        >
          Copyright © 2024 灵动创意工坊. All Rights Reserved.
        </div>
      </div>
      <Modal
        centered
        title="请完成以下校验以继续您的操作"
        open={verifyOpen}
        onOk={verifySubmit}
        confirmLoading={verifyConfirmLoading}
        onCancel={verifyCancel}
      >
        <div
          style={{
            marginTop: 30,
            minHeight: 60,
          }}
        >
          <Row gutter={12}>
            <Col span={18}>
              <Form name="verifyCodeForm">
                <Form.Item
                  label="验证码"
                  name="verifyCode"
                  rules={[{ required: true, message: '请输入验证码' }]}
                >
                  <Input size={'large'} value={verifyCode} placeholder="请输入右侧的验证码" />
                </Form.Item>
              </Form>
            </Col>
            <Col span={6}>
              <Image height={'40px'} width={'100%'} preview={false} />
            </Col>
          </Row>
        </div>
      </Modal>
    </div>
  );
};
export default Login;
